
import CryptoJS from "crypto-js"
// const CryptoJS =require('crypto-js')
import os from 'os'
import { WebSocket  } from "ws"

const APPID = 'cc69f09d'
const API_SECRET = 'ZDQ3YjFmNmNmOWRmOGM0MmI1ZDVmYmRh'
const API_KEY = '09a56431edd578b96f01ae2e2312e638'

function getWebsocketUrl() {
	return new Promise((resolve, reject) => {
		var apiKey = API_KEY
		var apiSecret = API_SECRET
		var url = 'wss://spark-api.xf-yun.com/v3.1/chat'
		var host = 'spark-api.xf-yun.com'
		var date = encodeURIComponent(new Date().toGMTString())
		var algorithm = 'hmac-sha256'
		var headers = 'host date request-line'
		var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`
		// var signatureSha = CryptoJS.createHmac(algorithm, apiSecret).update(signatureOrigin).digest();
		var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
		var signature = CryptoJS.enc.Base64.stringify(signatureSha)
		var authorizationOrigin =
			`api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
		var authorization = btoa(authorizationOrigin)
		url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
		resolve(url)
	})
}

class TTSRecorder {
	constructor({
		appId = APPID
	} = {}) {
		this.appId = appId
		this.status = 'init'
	}

	// 修改状态
	setStatus(status) {
		this.onWillStatusChange && this.onWillStatusChange(this.status, status)
		this.status = status
	}

	// 连接websocket
	connectWebSocket() {
		this.setStatus('ttsing')
		return getWebsocketUrl().then(url => {
			let ttsWS = new WebSocket(url) 
			this.ttsWS = ttsWS
			ttsWS.onopen = e => {
				this.webSocketSend()
			}
			ttsWS.onmessage = e => {
				this.result(e.data)
			}
			ttsWS.onerror = e => {
				clearTimeout(this.playTimeout)
				this.setStatus('error')
				console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`)
			}
			ttsWS.onclose = e => {
				console.log(e)
			}
		})
	}


	// websocket发送数据
	webSocketSend(text) {
		var params = {
			"header": {
				"app_id": this.appId,
				// "uid": "fd3f47e4-d"
			},
			"parameter": {
				"chat": {
					"domain": "generalv3",
					"temperature": 0.5,
					"max_tokens": 1024
				}
			},
			// "payload": {
			// 	"message": {
			// 		"text": [{
			// 				"role": "user",
			// 				"content": "中国第一个皇帝是谁？"
			// 			},
			// 			{
			// 				"role": "assistant",
			// 				"content": "秦始皇"
			// 			},
			// 			{
			// 				"role": "user",
			// 				"content": "秦始皇修的长城吗"
			// 			},
			// 			{
			// 				"role": "assistant",
			// 				"content": "是的"
			// 			},
			// 			{
			// 				"role": "user",
			// 				"content": $('#input_text').text()
			// 			}
			// 		]
			// 	}
			// }
            "payload": {
				"message": {
					"text": [
						{
							"role": "user",
							"content": text
						}
					]
				}
			}
		}
		console.log(JSON.stringify(params))
		this.ttsWS.send(JSON.stringify(params))
	}

	start(text) {
		this.connectWebSocket(text)
	}

	// websocket接收数据的处理
	result(resultData) {
		let jsonData = JSON.parse(resultData)
		console.log(resultData);
		

        //TODO:返回结果
		// 提问失败
		if (jsonData.header.code !== 0) {
			console.error(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`)
			return
		}
		if (jsonData.header.code === 0 && jsonData.header.status === 2) {
			this.ttsWS.close()
			bigModel.setStatus("init")
		}
	}
}


export {getWebsocketUrl,TTSRecorder};
